<template>
  <div class="max-w-3xl mx-auto p-6">
    <h1 class="text-2xl font-semibold">计数器（Counter）</h1>
    <p class="mt-4 text-gray-600">统计文本的字符、字数、行数、字节等，并提供常用操作（复制、下载、粘贴、加载文件）。</p>

    <div class="mt-6 space-y-4">
      <div class="flex items-center justify-between">
        <div class="text-sm text-gray-600">源文本（Source text）</div>
        <div class="text-sm text-gray-500">字符（含空格）：<span class="font-medium">{{ charCount }}</span>  字（估算）：<span class="font-medium">{{ wordCount }}</span>  行：<span class="font-medium">{{ lineCount }}</span></div>
      </div>

      <label class="block">
        <textarea v-model="inputText" rows="10" class="w-full p-3 border rounded resize-y" placeholder="在此粘贴或输入文本"></textarea>
      </label>

      <div class="flex items-center gap-3">
        <button @click="copyResult" class="bg-blue-600 text-white px-4 py-2 rounded">复制结果</button>
        <button @click="downloadResult" class="border px-3 py-2 rounded">下载结果</button>
        <button @click="reset" class="border px-3 py-2 rounded text-sm">清空</button>
        <button @click="pasteFromClipboard" class="border px-3 py-2 rounded text-sm">粘贴</button>
        <input type="file" accept=".txt" @change="onFileChange" class="text-sm" />
        <nuxt-link to="/text-tools" class="ml-auto text-sm text-blue-500">返回文本工具</nuxt-link>
      </div>

      <div class="pt-4 border-t">
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <div class="text-sm text-gray-600 mb-2">详细统计（Details）</div>
            <ul class="text-sm space-y-1">
              <li>字符（含空格）： <span class="font-medium">{{ charCount }}</span></li>
              <li>字符（不含空格）： <span class="font-medium">{{ charNoSpaceCount }}</span></li>
              <li>字（估算，按空白分割）： <span class="font-medium">{{ wordCount }}</span></li>
              <li>行数： <span class="font-medium">{{ lineCount }}</span></li>
              <li>非空行： <span class="font-medium">{{ nonEmptyLineCount }}</span></li>
              <li>字节大小（UTF-8）： <span class="font-medium">{{ byteSize }}</span></li>
            </ul>
          </div>

          <div>
            <div class="text-sm text-gray-600 mb-2">高频词（Top words）</div>
            <div class="text-sm bg-gray-50 p-3 border rounded h-36 overflow-auto">
              <div v-if="topWords.length === 0" class="text-gray-500">无词</div>
              <ol v-else class="list-decimal list-inside">
                <li v-for="(w, idx) in topWords" :key="idx">{{ w.word }} — {{ w.count }}</li>
              </ol>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useTools } from '~/composables/useTools'

const { copyToClipboard, downloadFile, readFile } = useTools()

const inputText = ref('')

const charCount = computed(() => inputText.value.length)
const charNoSpaceCount = computed(() => inputText.value.replace(/\s/g, '').length)

const wordsArray = computed(() => {
  if (!inputText.value) return []
  return inputText.value.trim().split(/\s+/).filter(Boolean)
})

const wordCount = computed(() => wordsArray.value.length)

const linesArray = computed(() => {
  if (!inputText.value) return []
  return inputText.value.split(/\r?\n/)
})

const lineCount = computed(() => (inputText.value === '' ? 0 : linesArray.value.length))
const nonEmptyLineCount = computed(() => linesArray.value.filter(l => l.trim().length > 0).length)

const byteSize = computed(() => {
  try {
    return new Blob([inputText.value]).size
  } catch (e) {
    return 0
  }
})

const topWords = computed(() => {
  const arr = wordsArray.value.map(w => w.toLowerCase())
  const map = new Map()
  for (const w of arr) {
    map.set(w, (map.get(w) || 0) + 1)
  }
  const list = Array.from(map.entries()).map(([word, count]) => ({ word, count }))
  list.sort((a, b) => b.count - a.count)
  return list.slice(0, 20)
})

const copyResult = async () => {
  const ok = await copyToClipboard(inputText.value)
  if (ok) alert('已复制到剪贴板')
  else alert('复制失败，请手动复制')
}

const downloadResult = () => {
  downloadFile(inputText.value, 'counter-result.txt', 'text/plain')
}

const reset = () => {
  inputText.value = ''
}

const pasteFromClipboard = async () => {
  try {
    const t = await navigator.clipboard.readText()
    inputText.value = t
  } catch (e) {
    console.error('读取剪贴板失败', e)
    alert('读取剪贴板失败')
  }
}

const onFileChange = async (e) => {
  const f = e.target.files && e.target.files[0]
  if (!f) return
  try {
    const content = await readFile(f)
    inputText.value = content
  } catch (err) {
    console.error('读取文件失败', err)
    alert('读取文件失败')
  } finally {
    e.target.value = ''
  }
}
</script>
